package cn.org.timespace.ons.inside.mina.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import cn.org.timespace.ons.inside.mina.filter.ESInProtocalPack;
import cn.org.timespace.ons.service.base.AppleServerService;
import cn.org.timespace.ons.service.base.MachinesService;
import cn.org.timespace.ons.service.policy.DataContentsService;
import cn.org.timespace.ons.service.policy.MomStatusService;
import cn.org.timespace.ons.util.StringUtil;
import cn.org.timespace.ons.util.SystemContext;
import cn.org.timespace.ons.vo.base.AppleServer;
import cn.org.timespace.ons.vo.base.DataContents;
import cn.org.timespace.ons.vo.base.Machines;
import cn.org.timespace.ons.vo.policy.MomStatus;

public class ProcessInPackage {
	private final static Log log = LogFactory.getLog(ProcessInPackage.class);
	
	/**
	 * 插入话单信息
	 * @param recordId
	 */
	public static void addDataContents(DataContents dataContents) {
		log.debug("插入话单信息：" + dataContents.getDcid());
		DataContentsService dataContentsService = (DataContentsService)SystemContext.getApplicationContext().getBean("dataContentsService");
		//保存话单
		dataContentsService.save(dataContents);
	}
	
	/**
	 * 插入数据交换状态信息
	 * @param recordId
	 */
	public static void addMomStatus(MomStatus momStatus) {
		log.debug("插入话单信息：" + momStatus.getMomid());
		MomStatusService momStatusService = (MomStatusService)SystemContext.getApplicationContext().getBean("momStatusService");
		//保存话单
		momStatusService.save(momStatus);
	}
	
	/**
	 * 根据信息终端的组合ID,获取信息终端
	 */
	public static Machines getMachine(String machinesGroupID){
		log.debug("信息终端的组合ID信息：" + machinesGroupID);
		MachinesService machinesService = (MachinesService)SystemContext.getApplicationContext().getBean("machinesService");
		Machines machines = machinesService.findByCondition(machinesGroupID);
		return machines;
	}
	
	/**
	 * 根据信息终端的组合ID,获取信息终端
	 */
	public static void updateMachine(Machines machines){
		log.debug("信息终端的组合ID信息：" + machines.getMachinesID());
		MachinesService machinesService = (MachinesService)SystemContext.getApplicationContext().getBean("machinesService");
		//根据信息终端的三码组合ID,及初次时间是否为空，获取信息终端
		machinesService.update(machines);
	}
	
	/**
	 * 根据信息终端的主键,获取信息终端
	 */
	public static Machines getMachineById(String mid){
		log.debug("信息终端的主键：" + mid);
		MachinesService machinesService = (MachinesService)SystemContext.getApplicationContext().getBean("machinesService");
		Machines machines = machinesService.findById(mid);
		return machines;
	}
	
	/**
	 * 根据信息终端的主键,获取信息终端
	 */
	public static AppleServer getAppleServerById(String mid){
		log.debug("信息终端的主键：" + mid);
		AppleServerService appleServerService = (AppleServerService)SystemContext.getApplicationContext().getBean("appleServerService");
		AppleServer appleServer = appleServerService.findById(mid);
		return appleServer;
	}
	
	
	/**
	 * 根据接收包结构取得回复包（机器号和功能号相同）
	 * @param pack
	 * @return
	 */
	public static ESInProtocalPack getPackReplay(ESInProtocalPack pack) {
		ESInProtocalPack packReplay = new ESInProtocalPack();
		packReplay.setSyncFrame(ESInProtocalPack.SYNC_FRAME_NAME_DOWN);
		packReplay.setMachineNo(pack.getMachineNo());
		packReplay.setFunctionNo(pack.getFunctionNo());
		return packReplay;
	}
	
	/**
	 * 字符串长度不足时，在最前面补 0
	 * @param digits  字符串应有长度
	 * @param str  字符串
	 * */
	public static String StrAddLength(int digits,String str){
		int len = str.length();
		if(len < digits){
			StringBuffer sb = new StringBuffer();
			for(int j = 0; j < digits - len; j++){
				sb.append("0");
			}
			str = sb.toString() + str;
		}
		return str;
	}
	
	/**
	 * 判断输入流是否以同步帧(SyncFrame)开头
	 * @param in
	 * @return
	 */
	public static boolean isStartWithSyncFrame(String inStr) {
		
		if(inStr == null)
			return false;
		
		if(inStr.startsWith(ESInProtocalPack.SYNC_FRAME_NAME_UP) || inStr.startsWith(ESInProtocalPack.SYNC_FRAME_NAME_DOWN))
			return true;
		
		return false;
	}
	
	/**
	 * 判断短时间内同一张卡是否出现同样的进出校状态
	 * @param session
	 * @param activeMsg
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isRepeatCard(IoSession session, String activeMsg, int filterInterval) {
		Map<String, String> cardRecordMap = ( Map )session.getAttribute("CardRecords");
		
		if(cardRecordMap == null) {
			cardRecordMap = new HashMap<String, String>();
		}
		
		String[] activeMsgs = activeMsg.split("/");
		
		String cardRecord = cardRecordMap.get(activeMsgs[0]);
		
		log.debug(activeMsg + "," + cardRecord);
		
		//首先将最新的放入到session中
		cardRecordMap.put(activeMsgs[0], activeMsg);
		session.setAttribute("CardRecords", cardRecordMap);
		
		if(StringUtil.notNull(cardRecord)) {
			try {
				String[] cardRecords = cardRecord.split("/");
				
				SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
				Date dateCardRecord = format.parse(cardRecords[1]);
				Date dateActiveMsg = format.parse(activeMsgs[1]);
			
				/*if(dateActiveMsg.getTime() - dateCardRecord.getTime() < 1 * 60 * 1000) {
					log.info("短时间内同一张卡有两条进出校记录,直接丢弃");
					return true;
				}*/
				
				log.debug("时间相差：" + (dateActiveMsg.getTime() - dateCardRecord.getTime()));
				log.debug("filterInterval=" + filterInterval * 60 * 1000);
				if(activeMsgs[2].equals(cardRecords[2]) && (dateActiveMsg.getTime() - dateCardRecord.getTime()) < filterInterval * 60 * 1000) {
					log.info("短时间内同一张卡连续出现同方向进出校状态,直接丢弃(" + activeMsg + ")");
					return true;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
			
		return false;
	}
	
	public static void main(String[] args) {
		//测试用
		for(int i = 0; i < 2000; i++) {
			//ProcessPackage.sendMessage("0000818819/110528070013/1/100000;");
		}
		
		try {
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		Date dateCardRecord = format.parse("110528070013");
		
		Date dateActiveMsg = format.parse("110528070514");
		
		System.out.println((dateActiveMsg.getTime() - dateCardRecord.getTime()) / 1000);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
